﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SerialPortComm
{
    public class CommonHelper
    {
        /// <summary>
        /// 十六进制字节数组转成字符串
        /// </summary>
        /// <param name="mStr"></param>
        /// <returns></returns>
        public static string HexToStr(byte[] bytes)
        {
            return BitConverter.ToString(bytes).Replace("-", " ");
        }

        /// <summary>
        /// 十六进制字符串转换十六进制数组
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static byte[] StrToHex(string str)
        {
            string[] nStr = str.Replace(' ', '-').Split('-');
            byte[] bytes = new byte[nStr.Length];
            for (int i = 0; i < nStr.Length && nStr[i].Length == 2; i++)
            {
                if (!byte.TryParse(nStr[i], NumberStyles.HexNumber, null, out bytes[i]))
                {
                    bytes[i] = 0;
                }
            }
            return bytes;
        }
    }
}
